package com.simulate;

import java.io.IOException;
import java.util.List;

import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

/**
 * 模拟位置的线程
 * @author wangqiuwei
 * @since 2015/9/10
 */
public class MockLocationThread extends Thread {

    private static final String TAG = MockLocationThread.class.getSimpleName();

    private final static int MSG_ONSEND = 0;
    private final static int MSG_ONFINISH = 1;

    private List<String> locations;

    private LocationManager mLctMgr;

    private String mocLocationProvider;

    private boolean isTaskTerminated = false;

    private int mPlayIdx = 0;

    private static OnGPSSendListener mListener;
    private static Context mContext;

    public interface OnGPSSendListener {
        void onSend(String track);
    }

    public MockLocationThread(LocationManager locationManager, Context context,
                              String mocLocationProvider, List<String> data) throws IOException {

        this.mLctMgr = locationManager;
        this.mocLocationProvider = mocLocationProvider;
        this.locations = data;

        isTaskTerminated = false;
        mContext = context;
    }

    public void registerOnSendListener(OnGPSSendListener listener) {
        mListener = listener;
    }

    private static Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            if (mListener == null){
                return;
            }
            switch (msg.what){
                case MSG_ONSEND:
                    mListener.onSend(msg.getData().getString("gps"));
                    break;
                case MSG_ONFINISH:
                    Toast.makeText(mContext, "已经到最后一条", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    @Override
    public void run() {

        while (!isTaskTerminated) {
            if (locations.size() == 0 || locations.size() <= (mPlayIdx + 1)) {
                Message.obtain(mHandler, MSG_ONFINISH).sendToTarget();
                break;
            }

            String str = locations.get(mPlayIdx);
            if (str.length() == 0) {
                break;
            }

            //文件约定格式：经度，纬度，速度，方向，与下一个轨迹的时间间隔(s)
            // Set one position
            String[] parts = str.split(" ");

            Location location = new Location(mocLocationProvider);
            location.setLongitude(Double.valueOf(parts[0]));
            location.setLatitude(Double.valueOf(parts[1]));
            location.setSpeed((float) (Float.valueOf(parts[2]) / 3.6));
            location.setBearing(Float.valueOf(parts[3]));

            int sleepTime = Integer.valueOf(parts[4]);

            Log.i(TAG, location.toString());

            // set the time in the location. If the time on this location
            // matches the time on the one in the previous set call, it will be
            // ignored
            location.setTime(System.currentTimeMillis());

            location.setAccuracy(5);
            location.setAltitude(0);

            mLctMgr.setTestProviderLocation(mocLocationProvider, location);

            Message.obtain(mHandler, MSG_ONSEND, str).sendToTarget();

            try {
                Thread.sleep(sleepTime * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void startUp() {
        if (Thread.interrupted() == false) {
            shutDown();
        }

        isTaskTerminated = false;
        this.start();
    }

    public void shutDown() {
        isTaskTerminated = true;
        this.interrupt();
    }

    public void interruptThread() {
        this.interrupt();
    }

    public void playLast() {
        if (!isTaskTerminated && (mPlayIdx - 2) >= 0) {
            interruptThread();
            mPlayIdx -= 2;
            Log.i(TAG, "playLast=" + mPlayIdx);
        }
    }

    public void playNext() {
        if (!isTaskTerminated && (mPlayIdx + 1) < (locations.size())) {
            mPlayIdx++;
            Log.i(TAG, "playNext=" + mPlayIdx);
        }
    }
}
